package com.itheima.web.request;
/**
 * 中文乱码解决方案
 * 弹幕说：乱码是因为字符流输用的字符集和网页的不同
 */

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/req4")
public class RequestDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.解决乱码：POST，getReader()
//        request.setCharacterEncoding("utf-8");

        
        //2.获取username
        String username = request.getParameter("username");
        System.out.println("解决乱码前："+username);

        //3.GET，获取参数的方式：getQueryString
        //乱码原因：Tomcat进行URL解码的时候，默认的字符集是ISO-8859-1
        //3.1对乱码数据进行编码，转换为字节数组
        /*byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);
        //3.2字节数组解码
        username = new String(bytes, StandardCharsets.UTF_8);*/
        //合并
        username= new String(username.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        System.out.println("解决乱码之后："+username);


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);

        //1.解决乱码：POST getReader()
//        request.setCharacterEncoding("UTF-8");  //设置字符输入流的编码
        //注意！一定要放在第一行，不然控制台还是会乱码
        //弹幕说：乱码是因为字符流输用的字符集和网页的不同


        //2.获取username
        String username = request.getParameter("username");
//        System.out.println(username);



    }
}